package com.heima.comment.service.impl;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.pojos.*;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentRepayService;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    UserFeign userFeign;
    @Autowired
    GreenTextScan greenTextScan;
    @Autowired
    MongoTemplate mongoTemplate;

    private final Integer size = 10;


    /**
     * 查询文章评论列表
     *
     * @param commentRepayDto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto commentRepayDto) {

        //1.参数校验
        if (commentRepayDto == null || commentRepayDto.getCommentId()== null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (commentRepayDto.getMinDate() == null) {
            commentRepayDto.setMinDate(new Date());
        }
        //2.根据文章id查询所有评论
        List<ApCommentRepay> commentRepayList = mongoTemplate.find(Query.query(Criteria.where("commentId").is(commentRepayDto.getCommentId())
                .and("createdTime").lt(commentRepayDto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))//排序
                .limit(size), ApCommentRepay.class);//每页大小

        if (commentRepayList == null || commentRepayList.size() == 0) {
            return ResponseResult.okResult();
        }
        //3.用户登录状态

        ApUser apUser = AppThreadLocalUtils.getUser();
        //4.未登录
        if (apUser == null) {
            return ResponseResult.okResult(commentRepayList);
        }
        //5.登录
        //所有评论id
        List<String> idList = commentRepayList.stream().map(apComment -> apComment.getId())
                .collect(Collectors.toList());
        //查询当前评论下的点赞列表
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(Query.query(Criteria.where("commentRepayId").in(idList)
                .and("operation").is(0)
                .and("authorId").is(apUser.getId())),  ApCommentRepayLike.class);

        //封装返回
        List<CommentRepayVo> commentRepayVoList = new ArrayList<>();
        if (commentRepayList != null && commentRepayList.size() > 0 && apCommentRepayLikes != null && apCommentRepayLikes.size() > 0) {
            commentRepayList.forEach(commentRepay -> {   //所有评论
                CommentRepayVo commentRepayVo = new CommentRepayVo();
                BeanUtils.copyProperties(commentRepay, commentRepayVo);
                apCommentRepayLikes.forEach(apCommentRepayLike -> {
                    if (commentRepay.getId().equals(apCommentRepayLike.getCommentRepayId())) {

                        commentRepayVo.setOperation((short) 0); //当前已点赞的评论回显
                    }
                });
                commentRepayVoList.add(commentRepayVo);
            });

        } else {   //对当前文章评论未点赞
            return ResponseResult.okResult(commentRepayList);
        }
        return ResponseResult.okResult(commentRepayVoList);
    }




    /**
     * 保存回复
     *
     * @param commentRepaySaveDto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto commentRepaySaveDto) {
        //1.参数校验
        if (commentRepaySaveDto == null || commentRepaySaveDto.getCommentId() == null || StringUtils.isBlank(commentRepaySaveDto.getContent()) || commentRepaySaveDto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前评论信息非法");
        }
        //2.用户是否登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.获取用户对象
        apUser = userFeign.findUserById(apUser.getId());
        if (apUser == null || apUser.getStatus() == 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "当前用户非法");

        }
        //4.评论内容审核（阿里云）
        try {
            Map map = greenTextScan.greenTextScan(commentRepaySaveDto.getContent());
            if (!map.get("suggestion").equals("pass")) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前评论信息不合规");
            }
        } catch (Exception e) {
            log.info("阿里云内容反垃圾审核失败");
        }

        //5.封装数据，保存评论
        ApCommentRepay apCommentRepay = ApCommentRepay.builder()
                .authorId(apUser.getId())
                .authorName(apUser.getName())
                .commentId(commentRepaySaveDto.getCommentId())
                .content(commentRepaySaveDto.getContent())
                .likes(0)
                .createdTime(new Date())
                .build();
        mongoTemplate.save(apCommentRepay);
        //文章评论回复数量+1
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(apCommentRepay.getCommentId())), ApComment.class);
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);
        //6.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 点赞回复的评论
     *
     * @param commentRepayLikeDto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto commentRepayLikeDto) {
        //1.参数校验
        if (commentRepayLikeDto == null || commentRepayLikeDto.getCommentRepayId() == null || commentRepayLikeDto.getOperation() < 0 || commentRepayLikeDto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.用户是否登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.当前评论是否存在
        ApCommentRepay apCommentRepay = mongoTemplate.findById(commentRepayLikeDto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //4.评论点赞行为
        //是否已点赞
        Query query = Query.query(Criteria.where("authorId").is(apUser.getId())
                .and("commentRepayId").is(commentRepayLikeDto.getCommentRepayId()));
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (apCommentRepayLike != null && commentRepayLikeDto.getOperation() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已点赞");
        }
        if (commentRepayLikeDto.getOperation() == 0) {
            //点赞
            ApCommentRepayLike commentRepayLike = new ApCommentRepayLike();
           commentRepayLike.setAuthorId(apUser.getId());
           commentRepayLike.setCommentRepayId(commentRepayLikeDto.getCommentRepayId());
           commentRepayLike.setOperation(commentRepayLikeDto.getOperation());
            mongoTemplate.save(commentRepayLike);
            //评论的点赞数+1
            apCommentRepay.setLikes( apCommentRepay.getLikes() + 1);
            mongoTemplate.save( apCommentRepay);
        } else {
            //取消点赞
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(apUser.getId())
                    .and("commentRepayId").is(commentRepayLikeDto.getCommentRepayId())), ApCommentRepayLike.class);
            //评论中打完点赞数—1
            apCommentRepay.setLikes(( apCommentRepay.getLikes() - 1 < 0) ? 0 :  apCommentRepay.getLikes() - 1);
            mongoTemplate.save( apCommentRepay);
        }

        //5.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
}
